/**
 * @Author:  renyc
 * @Date: 2023年3月6日11:16:52
 */
'use strict';

import DataProvider from "../DataProvider";

/**
 * @Author: renyc
 * @Date: 2023年3月6日11:16:28
 * @description CSV数据源的Provider，对CSV类型数据进行编码和解码
 * @格式：
 *  首行：字段列表
 *  次行：数据列表
  * options = {
        header : true,
        fields :  {
            x : "X",
            y : "Y"
        }
 */
class CsvProvider extends DataProvider{
    constructor(options){
        super(options);

        this._field_x = "X";
        this._field_y = "Y";
        this._header = true;

        /**
         * 分割符
         */
        this._delimiter = ",";
        /**
         * line结尾
         */
        this._eol = "\r\n";

        this._text = null;
        this._headers = [];
        this._rows = [];
        
        this._json = null;
    }

    /**
     * 将CSV的text解析为GeoJson
     * @param {@} text 
     */
    parseGeoJson(text){
        this._text = text;
        let lines = text.split(this._eol);
        if(lines.length==0){
            return;
        }

        this._headers = lines[0].split(this._delimiter);
        let no_x = this._findField(this._field_x);
        let no_y = this._findField(this._field_y);

        let json = {
            "type": "FeatureCollection",
            // name : this._name,
            "features" : []
        };

        let count = lines.length;
        for(let i = 1; i < count; i++){
            let line = lines[i].trim();
            if(line.length>0){
                let cells = lines[i].split(this._delimiter);                

                let feature = this._parseFeature(cells, no_x, no_y);
                if(feature){
                    this._rows.push(cells);
                    json["features"].push(feature);
                }
            }
        }
        this._json = json;
        return json;
    }

    /***
     * 根据字段名查找字段序号
     */
    _findField(fname){
        let count = this._headers.length;
        for(let i = 0; i < count; i++){
            if(this._headers[i]===fname){
                return i;
            }
        }
        return -1;
    }
    
    _parseFeature(cells, no_x, no_y){
        if(no_x<0||no_y<0){
            return;
        }

        let x = parseFloat(cells[no_x]);
        let y = parseFloat(cells[no_y]);

        let feature = {
            "type": "Feature", 
            "properties":{},
            "geometry":{
                "type" : "Point",
                "coordinates" : [x, y]
            }
        }

        let count = this._headers.length;
        for(let i = 0; i < count; i++){
            feature["properties"][this._headers[i]] = cells[i].replace(/\"+/g,"");
        }
        return feature;
    }
}

export default CsvProvider